﻿using Sc.Cache;
using Sc.Domain;
using Sc.Persistence;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sc.Service
{
    public class Car_FillGasolineService
    {
        /// <summary>
        /// 加油数据持久层
        /// </summary>
        private readonly Car_FillGasolineDAO dao = new Car_FillGasolineDAO();
        /// <summary>
        /// 待办事宜服务层
        /// </summary>
        private Sys_ToDoListService service = new Sys_ToDoListService();
        /// <summary>
        /// 意见数据持久层
        /// </summary>
        private OpinionsDAL oDao = new OpinionsDAL();
        /// <summary>
        /// 保存车辆加油
        /// </summary>
        /// <param name="ent">页面数据</param>
        /// <param name="list">附件列表</param>
        /// <returns></returns>
        public ReturnModel SaveData(Car_FillGasoline ent, IList<Sys_Attachments> list)
        {
            if (list != null && list.Count > 0)
            {
                ent.HasAttachments = true;
            }
            ent.ApproalUsers = "USER0;";
            ent.NodeCount = 1; ent.InstanceState = 3;
            try
            {
                var bussId = dao.Add(ent);
                if (list != null)
                {
                    new Sys_AttachmentsDAO().SaveAttachments(list, bussId);
                }
                ReturnModel succ = new ReturnModel() { SourceId = bussId, Message = "操作成功" };
                return succ;
            }
            catch (Exception ex)
            {
                ReturnModel err = new ReturnModel() { SourceId = 0, Message = ex.Message };
                return err;
            }
        }

        /// <summary>
        /// 获取加油申请列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="pageIndex">当前第几页</param>
        /// <returns></returns>
        public CommModel<Car_FillGasoline> GetList(int userId, int pageSize, int pageIndex)
        {
            Hashtable param = new Hashtable();
            param.Add("A1", pageIndex);
            param.Add("A2", pageSize);
            param.Add("A3", "AND UserId=" + userId);
            param.Add("A4", "Car_FillGasoline");
            param.Add("A5", "FgTime DESC");
            var ht = CommDAO.CommPagination(param);
            if (Convert.ToInt32(ht["record"]) > 0)
            {
                DataTable dt = ht["data"] as DataTable;
                List<Car_FillGasoline> list = new List<Car_FillGasoline>();
                foreach (DataRow item in dt.Rows)
                {
                    list.Add(DataRowToModel(item));
                }
                CommModel<Car_FillGasoline> ent = new CommModel<Car_FillGasoline>();
                ent.Data = list;
                ent.PageCount = Convert.ToInt32(ht["PageCount"]);
                ent.RecordCount = Convert.ToInt32(ht["record"]);
                return ent;
            }
            return null;
        }
        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Car_FillGasoline DataRowToModel(DataRow row)
        {
            Car_FillGasoline model = new Car_FillGasoline();
            if (row != null)
            {
                if (row["Id"] != null && row["Id"].ToString() != "")
                {
                    model.Id = int.Parse(row["Id"].ToString());
                }
                if (row["CarId"] != null && row["CarId"].ToString() != "")
                {
                    model.CarId = int.Parse(row["CarId"].ToString());
                }
                if (row["DriverId"] != null)
                {
                    model.DriverId = Convert.ToInt32(row["DriverId"].ToString());
                }
                if (row["FgTime"] != null && row["FgTime"].ToString() != "")
                {
                    model.FgTime = DateTime.Parse(row["FgTime"].ToString());
                }
                if (row["FgType"] != null && row["FgType"].ToString() != "")
                {
                    model.FgType = int.Parse(row["FgType"].ToString());
                }
                if (row["FgMoney"] != null && row["FgMoney"].ToString() != "")
                {
                    model.FgMoney = decimal.Parse(row["FgMoney"].ToString());
                }
                if (row["Remark"] != null)
                {
                    model.Remark = row["Remark"].ToString();
                }
                if (row["HasAttachments"] != null && row["HasAttachments"].ToString() != "")
                {
                    if ((row["HasAttachments"].ToString() == "1") || (row["HasAttachments"].ToString().ToLower() == "true"))
                    {
                        model.HasAttachments = true;
                    }
                    else
                    {
                        model.HasAttachments = false;
                    }
                }
                if (row["InstanceState"] != null && row["InstanceState"].ToString() != "")
                {
                    model.InstanceState = int.Parse(row["InstanceState"].ToString());
                }
                if (row["ApproalUsers"] != null)
                {
                    model.ApproalUsers = row["ApproalUsers"].ToString();
                }
                if (row["NodeCount"] != null && row["NodeCount"].ToString() != "")
                {
                    model.NodeCount = int.Parse(row["NodeCount"].ToString());
                }
            }
            return model;
        }

        /// <summary>
        /// 获取单个加油数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <summary>
        public Car_FillGasoline GetDetail(int id)
        {
            var tmp = this.dao.GetDetail(id);
            tmp.UserName = CommService.IntanceSys().GetUserById(tmp.UserId).Name;
            tmp.CarNo = ProjectCache.CarInfo[tmp.CarId].CarNo;
            tmp.BaseItemName = ProjectCache.BaseItem[tmp.BaseItemId].Name;
            if (tmp != null && tmp.HasAttachments)
                tmp.AttactList = new Sys_AttachmentsDAO().GetList("CFGS", id);
            tmp.OpinionList = new List<Opinions>();// new OpinionsBLL().GetList("CFGS" + id);
            return tmp;
        }
        /// <summary>
        /// 审批用车申请
        /// </summary>
        /// <param name="bid">业务ID</param>
        /// <param name="userId">当前用户Id</param>
        /// <param name="opa">操作</param>
        /// <param name="todoId">待办事宜ID</param>
        /// <param name="opContext">意见</param>
        /// <returns></returns>
        public ReturnModel Approal(int bid, int userId, int opa, int todoId,string opContext)
        {
            var ent = this.GetDetail(bid);
            if (ent == null) return new ReturnModel() { SourceId = 0, Message = "请上传正确的业务ID" };
            var upUsers = CommService.UpdateApproalUers(ent.ApproalUsers, userId, ent.NodeCount);
            var upNodeCount = CommService.IsUpdateNodeCount(ent.ApproalUsers, userId, ent.NodeCount);
            var list = new List<Sys_ToDoList>();
            if (opa == 1)//拒绝
            {
                ent.InstanceState = 2;
                Sys_ToDoList todo = new Sys_ToDoList();
                todo.ActionURL = string.Empty;
                todo.CreaterName = "系统";
                todo.Name = "您的加油申请已被拒绝";
                todo.Source = "CFGS" + ent.Id;
                todo.State = 0;
                todo.UrgencyDegree = 0;
                todo.UserId = ent.UserId;
                list.Add(todo);
            }
            else
            {
                if (ent.NodeCount == 1)
                {
                    ent.InstanceState = 3;
                    Sys_ToDoList todo = new Sys_ToDoList();
                    todo.ActionURL = string.Empty;
                    todo.CreaterName = "系统";
                    todo.Name = "您的加油申请已通过";
                    todo.Source = "CFGS" + ent.Id;
                    todo.State = 0;
                    todo.UrgencyDegree = 0;
                    todo.UserId = ent.UserId;
                    list.Add(todo);
                }
                else
                {
                    ent.InstanceState = 1;
                    if (upNodeCount < ent.NodeCount)
                    {
                        var nextUsers = CommService.FindNextUsers(ent.ApproalUsers, userId, ent.NodeCount);
                        var to = service.GetDetail(todoId);
                        for (int i = 0; i < nextUsers.Count; i++)
                        {
                            Sys_ToDoList todo = new Sys_ToDoList();
                            todo.ActionURL = to.ActionURL;
                            todo.CreaterName = "系统";
                            todo.Name = to.Name;
                            todo.Source = to.Source;
                            todo.State = 0;
                            todo.UrgencyDegree = 0;
                            todo.UserId = nextUsers[i];
                            list.Add(todo);
                        }
                    }
                }
            }
            try
            {
                ent.ApproalUsers = upUsers;
                ent.NodeCount = upNodeCount;
                var rs = ent.InstanceState == 2 ? service.UpdateAll("CFGS" + bid, 1) : service.Update(new Sys_ToDoList() { Id = todoId, State = 1 });
                if (list != null && list.Count > 0)
                    service.SaveToDoList(list);
                Opinions op = new Opinions()
                {
                    Context = opContext,
                    CreateTime = DateTime.Now,
                    Source = "CFGS" + ent.Id,
                    UserId = userId
                };
                oDao.Add(op);
                var bussId = this.dao.Update(ent);
                ReturnModel succ = new ReturnModel() { SourceId = bussId, Message = "操作成功" };
                return succ;
            }
            catch (Exception ex)
            {
                ReturnModel err = new ReturnModel() { SourceId = 0, Message = ex.Message };
                return err;
            }
        }
    }
}
